﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Data.Common;
using System.Text;
using System.Windows.Forms;

namespace SP.OpenSource.CDC.Monitor
{
    public partial class MonitorConfig : UserControl
    {
        String m_sConnectedConfigID = String.Empty;
        
        String m_sConnectionString = String.Empty;
        String m_sStateConnectionString = String.Empty;
        String m_sConnectedDBName = String.Empty;
        String m_sConnectedServerName = String.Empty;
        String m_sEncryptType = String.Empty;

        String m_sErrorMessage = String.Empty;
        String m_sFormTitle = "MonitorCDC - Configure Monitoring";

        DataSet m_dsConfigurations = new DataSet();
        String m_sExePath = String.Empty;

        String m_sFormExceptionMsg = "Exception raised by operation. Message: ";
        public MonitorConfig()
        {
            InitializeComponent();
        }
        public MonitorConfig(String sConnectionString, String sConnectedDBName, String sConnectedServerName, String sConnectedConfigID, String sEncryptType)
        {
            InitializeComponent();

            m_sConnectedConfigID = sConnectedConfigID;
            m_sConnectionString = sConnectionString;
            m_sConnectedDBName = sConnectedDBName;
            m_sConnectedServerName = sConnectedServerName;
            m_sEncryptType = sEncryptType;
            m_sExePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        }

        
        public bool LoadMonitorConfigForm()
        {
            try
            {
                chkUseDefaultSubject.Text = "Use default subject (CDC on " + m_sConnectedServerName + " needs immediate attention!)";
                if (false == LoadTemplates())
                    return false;

                //Check saved data.
                if (false == System.IO.File.Exists(m_sExePath + "\\Config\\Configuration.dat"))
                {
                    String sErrorMessage = "File " + m_sExePath + "\\Config\\Configuration.dat" + " not found.";
                    sErrorMessage += Environment.NewLine;
                    sErrorMessage += " Make sure read/write permissions on the file.";
                    
                    MessageBox.Show(sErrorMessage, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    return false;
                }


                //Clean data table to avoid duplication.
                if (null != m_dsConfigurations && m_dsConfigurations.Tables.Count > 0 && m_dsConfigurations.Tables[0].Rows.Count > 0)
                    m_dsConfigurations.Tables.RemoveAt(0);

                m_dsConfigurations.ReadXml(m_sExePath + "\\Config\\Configuration.dat", XmlReadMode.ReadSchema);

                if (null != m_dsConfigurations || m_dsConfigurations.Tables[0].Rows.Count > 1)
                {
                    DataRow[] drConnectedSys = m_dsConfigurations.Tables[0].Select("ConfigurationID=" + m_sConnectedConfigID);

                    if (drConnectedSys.Length > 0)
                    {
                        String sSMTPServerName = drConnectedSys[0]["SMTPServer"].ToString();
                        String sSMTPAuthRequired = drConnectedSys[0]["SMTPAuthRequired"].ToString(); 
                        String sEncryptionType = drConnectedSys[0]["PasswordEncryptionType"].ToString();
                        String sSMTPUserName = drConnectedSys[0]["SMTPUsername"].ToString();
                        String sSMTPPassword = drConnectedSys[0]["SMTPPassword"].ToString();
                        String sDefaultPort = drConnectedSys[0]["UseDefaultPort"].ToString();
                        String sPortNumber = drConnectedSys[0]["CustomPort"].ToString();
                        String sSSLRequired = drConnectedSys[0]["UseSSL"].ToString(); 

                        m_sErrorMessage = String.Empty;

                        if (sSMTPServerName.Length > 0)
                        {
                            txtSMTPServer.Text = sSMTPServerName;
                           
                            if (drConnectedSys[0]["UseSSL"].ToString() == "Yes")
                            {
                                chkSSL.Checked = true;
                                chkUseDefaultPort.Visible = false;
                                txtPort.Visible = true;
                                lblPort.Visible = true;
                                txtPort.Text = drConnectedSys[0]["CustomPort"].ToString();
                            }
                            else
                            {
                                chkSSL.Checked = false;
                                chkUseDefaultPort.Visible = true;
                                txtPort.Visible = false;
                                lblPort.Visible = false;
                                txtPort.Text = String.Empty;
                            }
                            if (drConnectedSys[0]["UseDefaultPort"].ToString() == "Yes")
                            {
                                chkSSL.Checked = true;
                                txtPort.Visible = true;
                                lblPort.Visible = true;
                                txtPort.Text = drConnectedSys[0]["CustomPort"].ToString();
                            }

                            txtFrom.Text = drConnectedSys[0]["EmailFrom"].ToString();
                            txtTo.Text = drConnectedSys[0]["EmailTo"].ToString();
                            if ("Yes" == drConnectedSys[0]["UseDefaultSubject"].ToString())
                            {
                                chkUseDefaultSubject.Checked = true;
                                txtSubject.Enabled = false;
                                txtSubject.Text = String.Empty;
                            }
                            else
                            {
                                txtSubject.Enabled = true;
                                chkUseDefaultSubject.Checked = false;
                                txtSubject.Text = drConnectedSys[0]["Subject"].ToString();
                            }
                            
                            if (drConnectedSys[0]["MessageTemplateName"].ToString().Length > 0)
                            {
                                drpTemplates.Text = drConnectedSys[0]["MessageTemplateName"].ToString();
                            }
                            else
                                drpTemplates.SelectedIndex = -1;

                            if (sSMTPAuthRequired == "Yes")
                            {
                                chkAuthRequired.Checked = true;
                                txtUsername.Text = drConnectedSys[0]["SMTPUsername"].ToString();
                            
                                //Decode & assign password
                                String sDecryPassword = String.Empty;
                                m_sErrorMessage = drConnectedSys[0]["SMTPPassword"].ToString();
                                m_sErrorMessage = String.Empty;
                                if (false == BLL.Crypt.Decrypt(drConnectedSys[0]["SMTPPassword"].ToString(), m_sEncryptType, ref sDecryPassword, ref m_sErrorMessage))
                                {
                                    MessageBox.Show("There was an error while decrypting password." + Environment.NewLine + "Error Message: " + m_sErrorMessage, "CDC Capture Data - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    m_sErrorMessage = String.Empty;
                                    return false;
                                }
                                txtPassword.Text = sDecryPassword;

                            }
                            else
                            {
                                chkAuthRequired.Checked = false;
                            }

                        }
                    }

                }
                return true;
            }
            catch(Exception ex)
            {
                MessageBox.Show(m_sFormExceptionMsg + ex.Message, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        private void chkUseDefaultPort_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (true == chkUseDefaultPort.Checked)
                {
                    lblPort.Visible = true;
                    txtPort.Visible = true;
                }
                else
                {
                    lblPort.Visible = false;
                    txtPort.Visible = false;
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(m_sFormExceptionMsg + ex.Message, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
        }

        private void chkSSL_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (true == chkSSL.Checked)
                {
                    chkUseDefaultPort.Checked = false;
                    chkUseDefaultPort.Visible = false;
                    lblPort.Visible = true;
                    txtPort.Visible = true;
                }
                else
                {
                    chkUseDefaultPort.Checked = true;
                    chkUseDefaultPort.Visible = true;
                    lblPort.Visible = false;
                    txtPort.Visible = false;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(m_sFormExceptionMsg + ex.Message, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private bool LoadTemplates()
        {
            try
            {
                Dictionary<string, string> test = new Dictionary<string, string>();

                foreach (string sFile in System.IO.Directory.GetFiles(m_sExePath + "\\EmailTemplates", "*.htm"))
                {
                    test.Add(sFile, System.IO.Path.GetFileNameWithoutExtension(sFile));                    
                }
                
                drpTemplates.DataSource = new BindingSource(test, null);
                drpTemplates.DisplayMember = "Value";
                drpTemplates.ValueMember = "Key";


                return true;
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                String sError = "There was an error while loadig template information.";
                sError += Environment.NewLine + Environment.NewLine;
                sError += ex.Message;

                MessageBox.Show(sError, m_sFormTitle + " - Load Template Information", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            try
            {
                if (drpTemplates.Text.Length > 0)
                {
                    EmailPreview oEmailPreview = new EmailPreview(drpTemplates.Text + ".htm");
                    oEmailPreview.ShowDialog();
                }
                else
                {
                    MessageBox.Show("Please select a template.", m_sFormTitle + " - Preview Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(m_sFormExceptionMsg + ex.Message, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnTestSMTPSettings_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                if (false == ValidateSMTPControls())
                {
                    Cursor.Current = Cursors.Default;
                    return;
                }
                BLL.CDCManagement m_oCDCManagement = new BLL.CDCManagement();
                String sCDCStatus = String.Empty;
                if (true == m_oCDCManagement.IsCDCEnabledDB(m_sConnectionString, m_sConnectedDBName, ref m_sErrorMessage))
                    sCDCStatus = "Enabled"; 
                else
                    sCDCStatus = "Disabled";

                String sSubject = String.Empty;
                if (chkUseDefaultSubject.Checked == true)
                    sSubject = "[CDC MONITORING TEST MESSAGE] CDC on " + m_sConnectedServerName + " needs immediate attention!";
                else
                    sSubject = "[CDC MONITORING TEST MESSAGE] " + txtSubject.Text;

                
                DataTable dtErrorLog = new DataTable("CDCErrorLog");
                m_sErrorMessage = String.Empty;
                BLL.Monitor.GetErrorLog(m_sConnectionString, ref dtErrorLog, ref m_sErrorMessage);

                BLL.EmailHelper oEmailHelper = new BLL.EmailHelper();
                String sMessageBody = oEmailHelper.PrepareMsg(m_sExePath+ "/EmailTemplates/", drpTemplates.Text + ".htm", m_sConnectedServerName, sCDCStatus,
                                      ref dtErrorLog,true);

                
                m_sErrorMessage = String.Empty;
                if (false == oEmailHelper.SendMailMessage(txtSMTPServer.Text, chkAuthRequired.Checked, txtUsername.Text, txtPassword.Text,
                                chkUseDefaultPort.Checked,chkSSL.Checked,
                                txtPort.Text, txtFrom.Text, txtTo.Text, sSubject, sMessageBody, ref m_sErrorMessage))
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("There was an error while sending email. Error Message: " + m_sErrorMessage, m_sFormTitle + " - Test SMTP Settings.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                Cursor.Current = Cursors.Default;
                MessageBox.Show("SMTP test successful. Please verify that your received test email message.", m_sFormTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("There was an error while sending email. Error Message: " + ex.Message, m_sFormTitle + " - Test SMTP Settings.", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool ValidateSMTPControls()
        {
            try
            {
                if (txtSMTPServer.Text.Length <= 0)
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("SMTP server cannot be empty.", m_sFormTitle + " - Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }

                if (txtTo.Text.Length <= 0)
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("\"Email To\"  cannot be empty.", m_sFormTitle + " - Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }

                if (txtFrom.Text.Length <= 0)
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("\"Email From\"  cannot be empty.", m_sFormTitle + " - Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }

                if (chkUseDefaultSubject.Checked == false)
                {
                    if (txtSubject.Text.Length <= 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("\"Email Subject\"  cannot be empty.", m_sFormTitle + " - Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }


                if (drpTemplates.Text.ToString().Length <= 0)
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("Please select an email template.", m_sFormTitle + " - Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }

                if (chkSSL.Checked == true || chkUseDefaultPort.Checked == false)
                {
                    if (txtPort.Text.ToString().Length <= 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Port number cannot be empty.", m_sFormTitle + " - Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }

                if (chkAuthRequired.Checked == true )
                {
                    if (txtUsername.Text.ToString().Length <= 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Username cannot be empty.", m_sFormTitle + " - Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                    if (txtUsername.Text.ToString().Length <= 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Username cannot be empty.", m_sFormTitle + " - Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    } 
                    if (txtPassword.Text.ToString().Length <= 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Password cannot be empty.", m_sFormTitle + " - Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(m_sFormExceptionMsg + ex.Message, m_sFormTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                if (false == ValidateSMTPControls())
                {
                    Cursor.Current = Cursors.Default;
                    return;
                }

                if (false == System.IO.File.Exists(m_sExePath + "\\Config\\Configuration.dat"))
                {
                    String sErrorMessage = "File " + m_sExePath + "\\Config\\Configuration.dat" + " not found.";
                    sErrorMessage += Environment.NewLine;
                    sErrorMessage += " Make sure read/write permissions on the file.";
                    sErrorMessage += Environment.NewLine;
                    sErrorMessage += "If problem persists, please contact SecurePublish: support@securepublish.com";

                    MessageBox.Show(sErrorMessage, "Configure Monitoring - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    return ;
                }


                //Clean data table to avoid duplication.
                if (null != m_dsConfigurations && m_dsConfigurations.Tables.Count > 0 && m_dsConfigurations.Tables[0].Rows.Count > 0)
                    m_dsConfigurations.Tables.RemoveAt(0);

                m_dsConfigurations.ReadXml(m_sExePath + "\\Config\\Configuration.dat", XmlReadMode.ReadSchema);

                String sEncryptedPass = String.Empty;
                if (null != m_dsConfigurations || m_dsConfigurations.Tables[0].Rows.Count > 1)
                {
                    DataRow[] drConnectedSys = m_dsConfigurations.Tables[0].Select("ConfigurationID=" + m_sConnectedConfigID);

                    if (drConnectedSys.Length > 0)
                    {
                        drConnectedSys[0]["SMTPServer"] = txtSMTPServer.Text;
                        if (chkAuthRequired.Checked == true)
                        {
                            drConnectedSys[0]["SMTPAuthRequired"] = "Yes";
                            if (false == BLL.Crypt.Encrypt(txtPassword.Text, m_sEncryptType, ref sEncryptedPass, ref m_sErrorMessage))
                            {
                                MessageBox.Show("There was an error encrypting password.", "Configure Monitoring - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }

                            drConnectedSys[0]["SMTPPassword"] = sEncryptedPass;
                            drConnectedSys[0]["SMTPUsername"] = txtUsername.Text;
                        }
                        else
                        {
                            drConnectedSys[0]["SMTPAuthRequired"] = "No";
                            drConnectedSys[0]["SMTPPassword"] = String.Empty;
                            drConnectedSys[0]["SMTPUsername"] = String.Empty;
                        }

                        

                        if (chkUseDefaultPort.Checked == true)
                            drConnectedSys[0]["UseDefaultPort"] = "Yes";
                        else
                        {
                            drConnectedSys[0]["UseDefaultPort"] = "No";
                            drConnectedSys[0]["CustomPort"] = txtPort.Text;
                        }

                        if (chkSSL.Checked == false)
                            drConnectedSys[0]["UseSSL"] = "No";
                        else
                        {
                            drConnectedSys[0]["CustomPort"] = txtPort.Text;
                            drConnectedSys[0]["UseSSL"] = "Yes";
                            drConnectedSys[0]["UseDefaultPort"] = "Yes";
                        }

                        drConnectedSys[0]["EmailFrom"] = txtFrom.Text;
                        drConnectedSys[0]["EmailTo"] = txtTo.Text;
                        if (chkUseDefaultSubject.Checked == true)
                        {
                            drConnectedSys[0]["UseDefaultSubject"] = "Yes";
                            drConnectedSys[0]["Subject"] = "CDC on " + m_sConnectedServerName + " needs immediate attention!";
                        }
                        else
                        {
                            drConnectedSys[0]["UseDefaultSubject"] = "No";
                            drConnectedSys[0]["Subject"] = txtSubject.Text;
                        }

                        drConnectedSys[0]["MessageTemplateName"] = drpTemplates.Text;                        
                        
                        m_sErrorMessage = String.Empty;
                    }
                    
                    m_dsConfigurations.AcceptChanges();

                    m_dsConfigurations.WriteXml(m_sExePath + "\\Config\\Configuration.dat", XmlWriteMode.WriteSchema);
                    MessageBox.Show("SMTP settings were saved.", m_sFormTitle,MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("There was an error while saving inforamtion. Looks like the product is not installed properly.", "Configure Monitoring - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;                 
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error while saving inforamtion. ", "Configure Monitoring - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor.Current = Cursors.Default;
            }
        }

        private void chkAuthRequired_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (chkAuthRequired.Checked == false)
                {
                    lblUsername.Visible = false;
                    lblPassword.Visible = false;
                    txtUsername.Visible = false;
                    txtPassword.Visible = false;
                }
                else
                {

                    lblUsername.Visible = true;
                    lblPassword.Visible = true;
                    txtUsername.Visible = true;
                    txtPassword.Visible = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(m_sFormExceptionMsg + ex.Message, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void chkUseDefaultSubject_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (chkUseDefaultSubject.Checked == true)
                    txtSubject.Enabled = false;
                else
                    txtSubject.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(m_sFormExceptionMsg + ex.Message, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

}
